package src.hash;

import java.util.Arrays;
import java.util.HashSet;

public class no349 {
//两个数组的交集

    public static void main(String[] args) {
        int[] arr1 = {4,9,5};
        int[] arr2 = {9,4,9,8,4};
        System.out.println(Arrays.toString(intersection(arr1, arr2)));
    }

    public static int[] intersection(int[] nums1, int[] nums2) {
        HashSet<Integer> set1 = new HashSet<>();   //set1存nums1数组去重后的元素
        HashSet<Integer> set2 = new HashSet<>();   //遍历nums2时判断set1中是否有该元素，都有的放入set2
        for (int i = 0; i < nums1.length; i++) {
            set1.add(nums1[i]);
        }
        for (int i : nums2) {
            if (set1.contains(i)) {
                set2.add(i);
            }
        }

        int[] res = new int[set2.size()];
        int i = 0;
        for (int j : set2) {
            res[i] = j;
            i++;
        }

        return res;

    }
}
